#!/usr/bin/env bash
# 
# A helper script that run a list of hook scripts in the given directory. It executes
# the script files in sequence and ignores the non-existing files.
# 
# Example: 
#
#   # ... <name> <dicretory> <file1> <file2> ...
#   ./hooks/run_hook "pre_compile" /app bin/pre-compile bin/pre_compile

name=$1
dir=$2

echo "Running ${name} hook"

cwd=$(pwd)
cd "${dir}" || exit 1
for ((i=3; i<=$#; i++)); do
    hook="${!i}"
    if [ -f "${hook}" ]; then
        echo "Running hook ${hook}"
        chmod +x "${hook}"
        "${hook}"
        code=$?
        if [ "${code}" = 0 ] ; then
            echo "Finished."
        else
            echo "Abort by exit code ${code}."
            exit "${code}"
        fi
    fi
done
cd "${cwd}" || exit 1
